############################################
# Copyright (c) 2018 
#
# Written by 
############################################
import os
import subprocess 
import win32con
from win32com.client import Dispatch
import win32print
from PyPDF2.pdf import PdfFileReader

import sys
sys.path.append(".")

from common.define import *
from lib.log import *

class FileOperation:
	def __init__(self, app, file, printerName=""):
		self.app = app
		self.file= file
		self.suffix = os.path.splitext(self.file)[1] 
		self.printerName = printerName # don't use
	def getPages(self):
		ret = RET_NG
		pp_debug("Suffix is %s" %(self.suffix))
		if (self.suffix == ".doc") or (self.suffix == ".docx") :
			#open Word
			word = Dispatch('Word.Application')
			word.Visible = False
			word.DisplayAlerts = False
			try:
				doc = word.Documents.Open(self.file, ReadOnly = 1)
			except:
				pp_error("Open file: %s failed!" %self.file)
				doc = None
				ret = RET_NG
			else:
				NumberOfPanges = doc.ComputeStatistics(2)
				pp_debug("the page number of %s  is %s" %(self.file, NumberOfPanges))
				doc.Close()
				ret = RET_OK
		elif (self.suffix == ".pdf"):
			try :
				f = open(self.file, "rb")
			except:
				pp_error("Open file %s failed!" %(self.file))
			else:
				pdf = PdfFileReader(f)
				NumberOfPanges = pdf.getNumPages()
				f.close()
				ret = RET_OK
		else: # default
			pp_error("Unkonw format file %s!" %(self.file))
			ret = RET_NG
		if ret == RET_OK:
			return NumberOfPanges
		else:
			return ret

	def sartPrint(self):
		ret = RET_NG
		if (self.suffix == ".doc") or (self.suffix == ".docx") :
			terminal_cmd = 'start cmd /c "timeout 5 & taskkill /f /im %s"' %(self.app.split("\\")[-1])
			cmd = '"%s" "%s" /mFilePrintDefault /mFileExit /q /n' %(self.app, self.file) 
			pp_debug("Cmd is [%s]" %(cmd))
			ret = RET_OK
		elif (self.suffix == ".pdf"):
			terminal_cmd = 'start cmd /c "timeout 10 & taskkill /f /im %s" /b' %(self.app.split("\\")[-1])
			cmd='"%s" /s /o /t "%s"' %(self.app, self.file) 
			pp_debug("Cmd is [%s]" %(cmd))
			ret = RET_OK
		else: # default
			pp_error("Unkonw format file %s!" %(self.file))
			ret = RET_NG
		if ( ret == RET_OK):
			pp_debug("Start run print command")
			print terminal_cmd
			os.system(terminal_cmd)
			proc = subprocess.Popen(cmd,shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			returncode = proc.wait()
			pp_debug("End run print command, return value is %s" %(proc.returncode))
		return ret

######################
# for win32print details, please refer to 
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd162863(v=vs.85).aspx
######################
class PrinterOperation:
	def __init__(self):
		self.perinter = win32print.GetDefaultPrinter()

	def OpenPrinter(self):
		printdefaults = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS}
		try:
			self.handle = win32print.OpenPrinter(self.perinter, printdefaults)
		except:
			pp_error("Open Printer Failed!")
			self.handle = None
			return RET_NG
		else:
			pp_debug("Open Printer succeed")
			return RET_OK

	def getPrinterAttributes(self, level=2):
		# level 2 is PRINTER_INFO_2
		try:
			attributes = win32print.GetPrinter(self.handle, level)
		except:
			pp_error("Get Printer Attributes Failed!")
			return None
		else:
			pp_debug("Get Printer Attributes succeed")
			return attributes

	def getPrinterStatus(self, attributes):
		if (attributes != None):
			pp_debug("Printer status is %s" %(attributes['Status']))
			return attributes['Status'] 

	def setDuplex(self, attributes, duplex):
		# DMDUP_SIMPLEX(1)    Normal (nonduplex) printing.
		# DMDUP_VERTICAL(3)   Long-edge binding, that is, the long edge of the page is vertical.
		ret = RET_OK
		level = 2 # PRINTER_INFO_2
		attributes['pDevMode'].Duplex = int(duplex)
		try:
			win32print.SetPrinter(self.handle, level, attributes, 0)
		except:
			pp_error("SetDuplex Failed!")
			ret = RET_NG
		else:
			pp_debug("Set duplex to %s correctly" %(duplex))
		return ret

	def setColor(self, attributes, color):
		# MONOCHROME(1)
		# COLOR(2) 
		ret = RET_OK
		level = 2 # PRINTER_INFO_2
		attributes['pDevMode'].Color = int(color)
		try:
			win32print.SetPrinter(self.handle, level, attributes, 0)
		except:
			pp_error("SetColor Failed!")
			ret = RET_NG
		else:
			pp_debug("Set color to %s correctly" %(color))
		return ret

	def setCopies(self, attributes, Copies):
		ret = RET_OK
		level = 2 # PRINTER_INFO_2
		attributes['pDevMode'].Copies = int(Copies)
		try:
			win32print.SetPrinter(self.handle, level, attributes, 0)
		except:
			pp_error("SetCopies Failed!")
			ret = RET_NG
		else:
			pp_debug("Set copiesto %s correctly" %(Copies))
		return ret

	def setPaperSize(self, attributes, papersize):
		# DMPAPER_A3 = 8
		# DMPAPER_A4 = 9
		# DMPAPER_A4SMALL = 10
		# DMPAPER_A5 = 11
		# DMPAPER_B4 = 12
		# DMPAPER_B5 = 13
		ret = RET_OK
		level = 2 # PRINTER_INFO_2
		attributes['pDevMode'].PaperSize = int(papersize)
		try:
			win32print.SetPrinter(self.handle, level, attributes, 0)
		except:
			pp_error("SetPaperSize Failed!")
			ret = RET_NG
		else:
			pp_debug("Set page size to %s correctly" %(papersize))
		return ret
	def closePrinter(self):
		win32print.ClosePrinter(self.handle)
